<template>
  <el-dialog
    title="拍照"
    :visible.sync="isUploadDialog"
    width="400px"
    :before-close="close"
    append-to-body
  >
    <video ref="video" autoplay></video>
    <button @click="takePhoto">拍照</button>
    <canvas ref="canvas" style="display: none;"></canvas>
    <img v-if="videoImg" :src="videoImg" alt="Photo" />
  </el-dialog>
</template>

<script>
export default {
  props: ["isUploadDialog"],
  data() {
    return {
      videoImg: ""
    }
  },
  methods: {
    close() {
      this.$emit("close");
    },
    takePhoto() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");


      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      this.videoImg = canvas.toDataURL("image/png");
    },
  },
  watch: {
    isUploadDialog(newValue) {
      if (newValue) {
        this.$nextTick(() => {
          navigator.mediaDevices
            .getUserMedia({ video: true, allow: "camera;microphone" })
            .then((stream) => {
              this.$refs.video.srcObject = stream;
            })
            .catch((error) => {
              console.error("Error accessing the camera:", error);
            });
        });
      }
    },
  },
  mounted() {},
};
</script>
